package com.ld.security.common.core.util;

import cn.hutool.extra.emoji.EmojiUtil;
import com.ld.security.common.core.anno.CrptKey;
import com.ld.security.common.core.constant.CrptCondition;
import com.ld.security.common.core.exception.ApiException;

/**
 * 只能对字符串属性使用
 */
public class CrptUtil {

    public static Object encrpt(Object obj){
        ReflectionUtil.applyAllDeclaredFields(obj,CrptKey.class,(anno, name, val) -> {
            if(val == null){
                return;
            } else if(val instanceof String){

            }else{
                ApiException.throw400("仅支持字符串属性");
            }
            String v = (String)val;
            if(anno.value() == CrptCondition.hash){
                v = UuidUtil.md5(v);
            }else if(anno.value() == CrptCondition.aes){
                v = AesUtil.encryptStr(v);
            }else if(anno.value() == CrptCondition.emoji){
                v = EmojiUtil.toAlias(v);
            }
            ReflectionUtil.invokeSetter(obj,name,v);
        });
        return obj;
    }

    public static Object decrpt(Object obj){
        ReflectionUtil.applyAllDeclaredFields(obj,CrptKey.class,(anno,name,val) -> {
            if(val instanceof String){

            }else{
                ApiException.throw400("仅支持字符串属性");
            }
            String v = (String)val;
            if(anno.value() == CrptCondition.aes){
                v = AesUtil.decryptStr(v);
            }else if(anno.value() == CrptCondition.emoji){
                v = EmojiUtil.toUnicode(v);
            }
            ReflectionUtil.invokeSetter(obj,name,v);
        });
        return obj;
    }

}
